package com.bizmda.bizsip.sink.connector;

import cn.hutool.extra.spring.SpringUtil;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizResultEnum;
import com.bizmda.bizsip.config.AbstractSinkConfig;
import com.bizmda.bizsip.config.SinkConfigMapping;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;

/**
 * 通讯适配器处理类
 *
 * @author shizhengye
 */
@Slf4j
public class Connector {
    private AbstractSinkConnector sinkConnector;

    /**
     * 根据sink-id获取通讯适配器调用接口
     *
     * @param sinkId Sink层模块的sink-id
     * @return 通讯适配器调用接口
     * @throws BizException BizException
     */
    public static Connector getSinkConnector(String sinkId) throws BizException {
        log.debug("获取Sink层通讯连接器:Connector.getSinkConnector({})", sinkId);

        Connector connector = new Connector();
        SinkConfigMapping sinkConfigMapping = SpringUtil.getBean("sinkConfigMapping");
        AbstractSinkConfig sinkConfig = null;
        try {
            sinkConfig = sinkConfigMapping.getSinkConfig(sinkId);
        } catch (BizException e) {
            log.error("获取Sink配置出错!", e);
            return null;
        }
        log.trace("Sink服务[{}]Connector配置: {}", sinkId, sinkConfig.getConnectorMap());

        if (sinkConfig.getConnectorMap() == null) {
            connector.sinkConnector = null;
            return connector;
        }
        String connectorType = (String) sinkConfig.getConnectorMap().get("type");

        Class<Object> clazz = (Class) AbstractSinkConnector.CONNECTOR_TYPE_MAP.get(connectorType);
        if (clazz == null) {
            throw new BizException(BizResultEnum.CONNECTOR_NOT_SET);
        }

        try {
            connector.sinkConnector = (AbstractSinkConnector) clazz.getDeclaredConstructor().newInstance();
            connector.sinkConnector.setType(connectorType);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            throw new BizException(BizResultEnum.CONNECTOR_JAVA_CLASS_CREATE_ERROR, e);
        }

        connector.sinkConnector.init(sinkConfig);

        return connector;
    }

    /**
     * 获取底层通讯适配器
     *
     * @return 底层通讯适配器对象
     */
    public AbstractSinkConnector getSinkConnector() {
        return this.sinkConnector;
    }

    /**
     * 调用通讯适配器进行交互处理
     *
     * @param inMessage 传入的消息报文字节流
     * @return 返回的消息报文字节流
     * @throws BizException Biz-SIP应用异常
     */
    public byte[] process(byte[] inMessage) throws BizException {
        if (!(this.sinkConnector instanceof ByteProcessInterface)) {
            throw new BizException(BizResultEnum.CONNECTOR_NO_BYTE_PROCESS_INTERFACE);
        }
        return ((ByteProcessInterface) this.sinkConnector).process(inMessage);
    }

}
